<template>
  <a-spin :spinning="loading">
    <titleName title="节点基本信息" />
    <custom-form
      ref="form"
      :is-validate="true"
      :edit-model="''"
      :rules="rules"
      :form="form"
      :form-list="formOption"
    >
      <div slot="promptLights" class="status-list">
        <img
          v-if="form.promptLights === 1 || form.promptLights === 2"
          :src="form.promptLights === 1 ? yellowLight : redLight"
          width="20"
          hight="20"
        />
        <div
          :class="color[form.statusLights]"
          class="prompt-lights"
        />
      </div>
      <template
        slot="completeDate"
        slot-scope="{data:{formItem:{disabled}}}"
      >
        <a-date-picker
          v-model="form.completeDate"
          :placeholder="disabled?'':'请选择'"
          :disabled-date="(current)=>{return completeDateDisabled(current)}"
          :disabled="useCompleteDate"
        />
      </template>
      <template
        slot="refList"
        slot-scope="{data:{formItem:{disabled}}}"
      >
        <a-tree-select
          v-model="form.refList"
          placeholder="请选择逾期类别"
          :tree-data="delayTypeTree"
          :replace-fields="replaceFields"
          show-search
          multiple
          labelInValue
          :disabled="disabled"
          :filter-tree-node="filterTreeNode"
        />
      </template>
    </custom-form>
    <template v-if="moment(form.endDate).diff(moment(form.completeDate), 'days') < 0">
      <titleName title="有效赶工措施" />
      <custom-form
        ref="form1"
        :is-validate="true"
        :edit-model="''"
        :rules="rules1"
        :form="form1"
        :form-list="formOption1"
      />
    </template>
    <titleName
      title="第三方完工确认单上传"
      class="margin-top"
    />
    <UploadTableNew
      ref="uploadTable"
      :mode="file1.mode"
      :init-file-list="file1.fileList"
      :need-page="file1.needPage"
      :use-add="useAdd"
      :business-code="file1.businessCode"
    />
    <titleName
      title="附件信息"
      style="margin-top:20px;"
    />
    <UploadTableNew
      ref="uploadTable"
      :mode="file2.mode"
      :init-file-list="file2.fileList"
      :need-page="file2.needPage"
      :use-add="useAdd"
      :business-code="file2.businessCode"
    />
    <!-- 选择审批人 -->
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
      :is-close-upper="false"
      @close="handleModalCancel(true)"
    />
    <div
      v-checkVisibleInDetail
      v-if="isAudit"
      class="page-btn-right-top"
    >
      <a-button @click="$close">关闭</a-button>
    </div>
    <!-- 选择审批人 -->
    <!-- 提交最后一个节点完成信息时弹窗 -->
    <BaseModal
      :visible="setCompleteModal.visible"
      title="阶段/类别完成情况"
      :width="1200"
      destroy-on-close
      @cancel="setCompleteModal.visible = false"
    >
    <div>
      <a-form-model :model="setCompleteModal">
          <a-form-model-item style="margin-bottom: 0;">
            <span>该节点为当前阶段/类别下最后一个节点，该节点完成后，其父级任务是否已全部完成？</span>
            <span style="color: red;margin-bottom: 0;">若选择是，则该父级节点不再生成至下月计划中。</span>
          </a-form-model-item>
          <a-form-model-item>
            <span>“{{ setCompleteModal.name }}”是否全部完成：</span>
            <a-switch v-model="setCompleteModal.isComplete" checked-children="是" un-checked-children="否"></a-switch>
          </a-form-model-item>
      </a-form-model>
    </div>
    <template slot="footer">
      <a-button @click="setCompleteModal.visible = false">
        取消
      </a-button>
      <a-button
        type="primary"
        @click="handleNodeComplete"
      >
        确定
      </a-button>
    </template>
  </BaseModal>
  <!-- 提交最后一个节点完成信息时弹窗 -->
  </a-spin>
</template>
<script>
import { formOption, formOption1 } from '../model.js'
import constructionSchedule from '@/api/construction/constructionSchedule'
import monthPlanApi from '@/api/construction/monthPlanApi'
import { TreeSelect } from 'ant-design-vue'
import BaseModal from '@/components/BaseModal'
export default {
  name: 'NodeMaintainPage',
  props: {
    // 节点信息
    source: {
      type: Object,
      default: () => {}
    },
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    },
    loading: {
      // 加载
      type: Boolean,
      default: false
    },
    submiting: {
      // 提交
      type: Boolean,
      default: false
    }
  },
  components: {
    ATreeSelect: TreeSelect,
    BaseModal,
  },
  data() {
    return {
      // 提交最后一个节点完成信息时弹窗：
      setCompleteModal: {
        hasSetComplete: false,
        visible: false,
        isComplete: false,
        name: '',
      },
      // 数据
      data: this.isAudit ? { type: 'detail' } : this.source,
      // 节点完成信息表单
      form: {},
      // 节点完成信息校验
      rules: {
        completeDate: [{ required: true, message: '请选择实际完成时间', trigger: 'change' }],
        refList: [{ required: true, message: '请选择逾期类别', trigger: 'change' }],
        delayReason: [{ required: true, message: '请选输入逾期原因', trigger: 'change' }],
        remarks: [{ required: true, message: '请选输入备注', trigger: 'change' }]
      },
      // 有效赶工措施表单
      form1: {},
      // 红灯
      redLight: require('@/assets/icons/redLight.png'),
      // 黄灯
      yellowLight: require('@/assets/icons/yellowLight.png'),
      // 第三方完工确认单上传
      file1: {
        // 处理操作的模式：'add'模式下，删除操作会调用文件删除接口，'edit'模式只会在表格中移除删除数据，不会调用接口
        mode: 'add',
        // 上传文件的业务编码
        businessCode: 'PM02',
        // 是否需要分页
        needPage: false,
        // 初始化文件列表
        fileList: []
      },
      // 附件信息上传
      file2: {
        // 处理操作的模式：'add'模式下，删除操作会调用文件删除接口，'edit'模式只会在表格中移除删除数据，不会调用接口
        mode: 'add',
        // 上传文件的业务编码
        businessCode: 'PM03',
        // 是否需要分页
        needPage: false,
        // 初始化文件列表
        fileList: []
      },
      // 逾期类别树
      delayTypeTree: [],
      // 逾期类别树字段替换
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'value',
        value: 'value'
      },
      // 实际完成时间禁用
      useCompleteDate: false,
      // 流程配置
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      // 业务id
      businessId: null,
      // 节点颜色
      color: {
        0: 'class-slider-0',
        1: 'class-slider-1',
        2: 'class-slider-2',
        3: 'class-slider-3',
        4: 'class-slider-4'
      }
    }
  },
  computed: {
    // 节点完成信息表单项
    formOption() {
      this.$checkRequireItem()
      // 状态（1：审核中/2：按期完成/3：逾期完成/4：审核不通过/5：全部完成/6：未全部完成/7:待开始/8:进行中 9预期未完成 10 未全部完成（最后一个节点）
      // 查看(基本信息)
      const { completeDate, endDate } = this.form
      let list = this.$clone(formOption)
      if (this.moment(endDate).diff(this.moment(completeDate), 'days') < 0) {
        list = list.filter(el => el.keyName !== 'remarks')
      } else {
        list = list.filter(el => el.keyName !== 'refList' && el.keyName !== 'delayReason')
      }
      return list.map((el) => {
          // 查看
          if (this.data.type === 'detail') {
            el.disabled = true
          } else {
            // 维护
            // 状态（1：审核中/2：按期完成/3：逾期完成/4：审核不通过/5：全部完成/6：未全部完成/7:待开始/8:进行中 9预期未完成 10 未全部完成（最后一个节点）
            const status = this.data.status
            if (status === 4 || status === 7 || status === 8 || status === 9) {
              const arr = ['completeDate', 'refList', 'delayReason', 'remarks']
              if (!arr.includes(el.keyName)) {
                el.disabled = true
              } else {
                el.disabled = false
              }
            } else {
              el.disabled = true
            }
          }
          return el
        })
    },
    // 有效赶工措施表单项
    formOption1() {
      // 查看
      const list = this.$clone(formOption1)
      if (this.data.type === 'detail') {
        return list.map((el) => {
          const item = this.$clone(el)
          item.disabled = true
          return item
        })
      } else {
        return list
      }
    },
    // 有限赶工措施表单校验
    rules1() {
      const obj = {}
      formOption1.forEach((item) => {
        if (item.rules) {
          obj[item.keyName] = item.rules
        }
      })
      return obj
    },
    // 文件上传按钮
    useAdd() {
      // 状态（1：审核中/2：按期完成/3：逾期完成/4：审核不通过/5：全部完成/6：未全部完成/7:待开始/8:进行中 9预期未完成 10 未全部完成（最后一个节点）
      const status = this.data.status
      if (this.data.type === 'detail') {
        return (status === 2 || status === 3) && !this.isAudit
      } else {
        return (status === 4 || status === 7 || status === 8 || status === 9) && !this.isAudit
      }
    }
  },
  watch: {
    'form1.laborResFee'() {
      this.computeRushFee()
    },
    'form1.equipResFee'() {
      this.computeRushFee()
    },
    'form1.materialResFee'() {
      this.computeRushFee()
    },
    'form1.safetyMeasureFee'() {
      this.computeRushFee()
    }
  },
  async created() {
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('month_plan_node')
  },
  mounted() {
    this.getDelayType()
    if (this.isAudit) {
      this.getData()
    }
  },
  methods: {
    /**
     * @description: 格式化时间
     * @param {object/string} date 时间对象或字符串
     * @param {boolean} toMoment 是否转换为Moment
     * @return {object} moment时间格式
     */
    formatDate(date, toMoment = true) {
      if (date?._isAMomentObject) {
        return toMoment ? date : date.format('YYYY-MM-DD')
      } else {
        return toMoment ? this.moment(date) : date
      }
    },
    /**
     * @description: 计算预计赶工费用
     * @param {void}
     * @return {void}
     */
    computeRushFee() {
      // 解决浮点加法运算精度问题
      const { laborResFee, equipResFee, materialResFee, safetyMeasureFee } = this.form1
      const arr = [laborResFee ?? 0, equipResFee ?? 0, materialResFee ?? 0, safetyMeasureFee ?? 0]
      let l = []
      arr.forEach((el) => {
        l.push(el.toString().split('.')[1]?.length || 0)
      })
      const lng = Math.max(...l)
      let num = 0
      arr.forEach((el) => {
        num += el * Math.pow(10, lng)
      })
      this.form1.rushFee = num / Math.pow(10, lng)
    },
    /**
      * @description:
      * 实际完成时间选择规则：与总计划一致，有10天的规则限制。原规则如下：
      * 1）常规情况下的节点实际完成时间规则如下：
      * ①计划完成时间≥当前完成时间，实际完成时间可选择≤当前时间的任意日期
      * ②计划完成时间＜当前时间，且当前时间-计划完成时间≤10天的，计划完成时间≤实际完成时间≤当前时间，在此区间内选择
      * ③计划完成时间＜当前时间，且当前时间-计划完成时间＞10天的，实际完成时间=当前时间，不可修改
      * 2）新的月计划审批通过后，节点“计划完成时间”早于月计划审批通过时间的，在维护节点时，“实际完成时间”可以选择小于等于当前时间的任意时间
      * 3）月计划调整审批通过后，调整过的节点（含修改和新增的节点），在维护节点时，“实际完成时间”可以选择小于等于当前时间的任意时间
      * @param {object} current 当前时间对象
      * @return {void}
      */
    completeDateDisabled(current) {
      const currentDate = this.moment(current).format('YYYY-MM-DD')
      const nowDate = this.moment().format('YYYY-MM-DD')
      const endDate = this.moment(this.form.endDate).format('YYYY-MM-DD')
      const date = this.moment(endDate).diff(nowDate, 'days')
      // 月计划调整审批通过后，调整过的节点（含修改和新增的节点），在维护节点时
      // isAdjustNode: 0,
      // 新的月计划审批通过后，节点“计划完成时间”早于月计划审批通过时间的
      // passTime: '',
      const passTime = this.$route.query.passTime
      const passTimeDate = this.moment(passTime).format('YYYY-MM-DD')
      if (!!this.form.isAdjustNode || (!!passTime && this.moment(endDate).diff(passTimeDate, 'day') <= 0)) {
        return current && this.moment(currentDate).diff(nowDate, 'days') > 0
      } else {
        if (date >= 0) {
          return current && this.moment(currentDate).diff(nowDate, 'days') > 0
        } else if (date < 0 && date >= -2){
          return current && (this.moment(currentDate).diff(nowDate, 'days') > 0 || this.moment(currentDate).diff(endDate, 'days') < 0)
        } else {
          return current && (this.moment(currentDate).diff(nowDate, 'days') != 0)
        }
      }
    },
    /**
     * @description: 获取逾期类型
     * @param {void}
     * @return {void}
     */
    getDelayType() {
      constructionSchedule.labelTreeList({ pageNo: 1, pageSize: 1000, type: 11 }).then(({ code, data }) => {
        if (code === 200) {
          this.delayTypeTree = data
          this.delayTypeTree.forEach(item=>{
            item['disabled'] = false
          })
        }
      })
    },
    /**
     * @description: 获取节点维护信息
     * @param {void}
     * @return {void}
     */
    getData() {
      this.$emit('update:loading', true)
      monthPlanApi.getFinalResult({id: this.isAudit ? this.$route.query.businessId : this.data.id}).then(res => {
        if (res.data) {
          const data = this.$clone(res.data)
          if (data.refList && data.refList.length > 0) {
            data.refList = data.refList.map(item => {
              const json = {
                value: item.typeId,
                label: item.typeName,
              }
              return json
            })
          }
          this.businessId = this.isAudit ? null : this.data.id
          if (this.data.type !== 'detail') {
            data.createName = JSON.parse(sessionStorage.getItem('ycloud-user_info')).name
            data.createTime = this.moment().format('YYYY-MM-DD')
          }
          this.form = data
          this.form1 = data
          const nowDate = this.moment().format('YYYY-MM-DD')
          const endDate = this.moment(this.form.endDate).format('YYYY-MM-DD')
          // 计划完成时间＜当前时间，且当前时间-计划完成时间＞10天的，实际完成时间=当前时间，不可修改
          if (this.moment(nowDate).diff(endDate, 'days') > 10 && this.data.type !== 'detail') {
            this.form.completeDate = this.moment()
          }
          //设置附件
          this.file1.fileList =
            this.form1.thirdFiles && this.form1.thirdFiles.map((el) => {
              el.useDelete = (this.source?.type || 'detail') === 'detail' ? false : true
              return el
            }) || []
          this.file2.fileList =
            this.form1?.files && this.form1.files.map((el) => {
              el.useDelete = (this.source?.type || 'detail') === 'detail' ? false : true
              return el
            }) || []
          // 实际完成时间是否禁用
          // 是否查看
          if (this.data.type === 'detail') {
            this.useCompleteDate = true
          } else {
            this.useCompleteDate = false
          }
        }
      }).finally(() => {
        this.$emit('update:loading', false)
      })
    },
    /**
     * @description: 提交审批
     * @param {void}
     * @return {void}
     */
    handleSubmit() {
      try {
        const vm = this
        if (vm.data.type === 'detail') {
          this.$confirm({
            title: '是否确定提交?',
            content: '',
            onOk() {
              vm.$emit('update:submiting', true)
              // 查看
              let fun = monthPlanApi.addResult
              fun({
                workId: vm.data.id,
                thirdFileIds: vm.file1.fileList ? vm.file1.fileList.map(item => item.commonId) : [],
                fileIds: vm.file2.fileList ? vm.file2.fileList.map(item => item.commonId) : []
              })
                .then(({ code }) => {
                  if (code === 200) {
                    vm.$message.success('提交成功！')
                    vm.handleModalCancel(true)
                  }
                })
                .finally(() => {
                  vm.$emit('update:submiting', false)
                })
            }
          })
        } else {
          // 节点完成(维护修改而来)
          vm.$refs.form.validate((valid) => {
            if (valid) {
              const { completeDate, endDate } = vm.form
              if (vm.moment(endDate).diff(vm.moment(completeDate), 'days') < 0) {
                vm.$refs.form1.validate((valid1) => {
                  if (valid1) {
                    vm.submitFun()
                  }
                })
              } else {
                vm.submitFun()
              }
            }
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * @description: 提交方法
     * @param {void}
     * @return {void}
     */
     submitFun() {
      try {
        if (this.form.isFinal) {
          this.setCompleteModal = {
            visible: true,
            hasSetComplete: false,
            isComplete: false,
            name: this.data.parentName,
          }
        } else {
          this.setProcessConfig = this.processConfig
          this.submitApprovalConfirm(this.setProcessConfig, (flag) => {
            if (!flag) return
            this.submitMethodLastNode()
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    submitMethodLastNode() {
      let params = {}
      // 状态（1：审核中/2：按期完成/3：逾期完成/4：审核不通过/5：全部完成/6：未全部完成/7:待开始/8:进行中 9预期未完成 10 未全部完成（最后一个节点）
      const { completeDate, endDate, delayReason, refList, remarks } = this.form
      if (this.moment(endDate).diff(this.moment(completeDate), 'days') < 0) {
        params = {
          ...this.form1,
          delayTypeId: refList ? refList.map(item => item.value) : [],
          thirdFileIds: this.file1.fileList.map(item => item.commonId) || [],
          fileIds: this.file2.fileList.map(item => item.commonId) || [],
          completeDate: this.formatDate(completeDate, false),
          delayReason,
          refList: refList ? refList.map(item => {
            item.typeId = item.value
            item.typeName = item.label
            return item
          }) : [],
          workId: this.data.id,
          isComplete: this.setCompleteModal.hasSetComplete ? this.setCompleteModal.isComplete : null,
        }
      } else {
        params = {
          thirdFileIds: this.file1.fileList ? this.file1.fileList.map(item => item.commonId) : [],
          fileIds: this.file2.fileList ? this.file2.fileList.map(item => item.commonId) : [],
          completeDate: this.formatDate(completeDate, false),
          remarks,
          workId: this.data.id,
          isComplete: this.setCompleteModal.hasSetComplete ? this.setCompleteModal.isComplete : null,
        }
      }
      this.$emit('update:submiting', true)
      let fun = monthPlanApi.addResult
      fun(params)
        .then(({ code }) => {
          if (code === 200) {
            // 设置businessId触发审批人弹框
            this.businessId = this.data.id
            this.$message.success('提交成功！')
            // 不选择审批人时二次弹框手动关闭
            if (parseInt(this.setProcessConfig) === 4) {
              this.handleModalCancel(true)
            }
          }
        })
        .finally(() => {
          this.$emit('update:submiting', false)
        })
    },
    /**
     * @description: 下拉树形框搜索过滤
     * @param {string} input 输入值
     * @param {object} option 下拉对象
     * @return {boolean} 是否符合过滤条件
     */
    filterTreeNode(input, treeNode) {
      return treeNode.componentOptions.propsData.title.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /**
     * @description: 关闭
     * @return {void}
     */
    handleclose() {
      this.form = {}
      this.form1 = {}
      this.file1.fileList = []
      this.file2.fileList = []
    },
    /**
     * @description: 关闭模态框
     * @param {boolean} 是否需要刷新
     * @return {void}
     */
    handleModalCancel(refresh = false) {
      this.handleclose()
      this.$emit('handleModalCancel', refresh)
    },
    /**
     * @description: 设置完成
     */
     handleNodeComplete() {
      this.setCompleteModal.hasSetComplete = true
      this.setCompleteModal.visible = false
      this.setProcessConfig = this.processConfig
      this.submitApprovalConfirm(this.setProcessConfig, (flag) => {
        if (!flag) return
        this.submitMethodLastNode()
      })
    },
  }
}
</script>
<style lang="less" scoped>
.status-list{
  display: flex;
  align-items: center;
  margin-top: 7px;
  img{
    margin-right: 10px;
  }
}
.prompt-lights {
  width: 59px;
  height: 23px;
  display: flex;
  align-items: center;
  justify-content: center;
}
// .class-0 {
// background-color: #d1d1d1;
// }
// .class-1 {
// background-color: #fff;
// }
.class-2 {
  background-color: #f85c62;
}
.class-3 {
  background-color: #1dc682;
}
.class-4 {
  background-color: #ffced0;
}
.margin-top {
  margin-top: 20px;
}
</style>

